﻿using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Runtime.Caching;
using pandx.Mulan.Authorization;
using pandx.Mulan.Caching.Dto;

namespace pandx.Mulan.Caching
{
    public class CachingAppService:MulanAppServiceBase,ICachingAppService
    {
        private readonly ICacheManager _cacheManager;

        public CachingAppService(ICacheManager cacheManager)
        {
            _cacheManager = cacheManager;
        }
        
        [AbpAuthorize(AppPermissions.Pages_Administration_Maintenances_Browse)]
        public ListResultDto<CacheDto> GetAllCaches()
        {
            var caches = _cacheManager.GetAllCaches()
                .Select(cache => new CacheDto
                {
                    Name = cache.Name
                }).ToList();

            return new ListResultDto<CacheDto>(caches);
        }
        
        private async Task ClearCache(EntityDto<string> input)
        {
            var cache = _cacheManager.GetCache(input.Id);
            await cache.ClearAsync();
        }
        [AbpAuthorize(AppPermissions.Pages_Administration_Maintenances_Clear)]
        public async Task ClearAllCaches()
        {
            var caches = _cacheManager.GetAllCaches();
            foreach (var cache in caches)
            {
                await cache.ClearAsync();
            }
        }
    }
}